package cn.itcast.bos.web.action;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.constant.Constants;
import cn.itcast.bos.utils.MailUtils;
import cn.itcast.bos.utils.SmsDemoUtils;
import cn.itcast.bos.web.action.common.BaseAction;
import cn.itcast.crm.domain.Customer;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class CustomerAction extends BaseAction<Customer> {
	// 注入redis缓存数据库模板对象
	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	// 前端bos_fore系统作为短信验证码的生产者，将消息生产后交给第三方系统bos_sms消费
	// 将Queue类型的JmsTemplate注入
	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;

	// 发送短信校验码
	@Action(value = "customer_sendSms", results = { @Result(name = "success", type = "json") })
	public String sendSms() throws Exception {
		// 生成随机验证码
		final String number = SmsDemoUtils.getNumber();
		// 从模型驱动中获取页面输入的手机号
		final String telephone = model.getTelephone();
		// 将生成的验证码存入seesion中，并设置过期时间，用于注册时调用
		ServletActionContext.getRequest().getSession().setAttribute(telephone, number);
		ServletActionContext.getRequest().getSession().setMaxInactiveInterval(1 * 60);// 1分钟后session失效
		// 调用MQ服务发送短信
		jmsTemplate.send("bos_sms", new MessageCreator() {
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", telephone);
				mapMessage.setString("code", number);
				return mapMessage;
			}
		});
		// 调用阿里大鱼发送验证码
		// SendSmsResponse response = SmsDemoUtils.sendSms(telephone, number);
		// if(response.getCode().equals("OK")) {
		/*
		String sendSms = "OK";
		if (sendSms.equals("OK")) {
			// 短信发送成功
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("success", number);// 将发送成功的验证码放入值栈中，方便页面获取
			// 优化页面效果，将手机号也入值栈,完成在页面回显手机号和验证码
			map.put("telephone", telephone);
			// map.put("code", number);//这行代码多余，上面的success对应的session中已经存放了验证码
			ServletActionContext.getContext().getValueStack().push(map);
		} else {
			// 短信发送失败
			throw new RuntimeException("发送信息失败，请重新发送！");
		}
		*/
		return SUCCESS;
	}

	// 用户注册
	// 属性驱动获取页面输入的验证码
	private String checkcode;

	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}

	@Action(value = "customer_regist", results = {
			@Result(name = "success", type = "redirect", location = "signup-success.html"),
			@Result(name = "input", type = "redirect", location = "signup.html") })
	public String regist() {
		// 从session中获取之前的验证码，与页面输入的验证码比对
		String code = (String) ServletActionContext.getRequest().getSession().getAttribute(model.getTelephone());
		if (code == null || !code.equals(checkcode)) {
			return INPUT;
		}
		// 调用crm-management系统完成客户的保存操作
		WebClient.create(Constants.CRM_MANAGEMENT_URL + "/services/customerService").path("/customer")
				.type(MediaType.APPLICATION_JSON).post(model);

		// 发送一封激活邮件
		// 生成32位激活码
		String activecode = RandomStringUtils.randomNumeric(32);
		// 将激活码存入redis数据库中，保存时间设置为24小时
		redisTemplate.opsForValue().set(model.getTelephone(), activecode, 24, TimeUnit.HOURS);
		// 调用mailUtils发送激活邮件
		String content = "尊敬的客户您好，请于24小时内，进行邮箱账户的绑定，点击下面地址完成绑定:<br/><a href='" + MailUtils.activeUrl + "?telephone="
				+ model.getTelephone() + "&activecode=" + activecode + "'>速运快递邮箱绑定地址</a>";
		MailUtils.sendMail("速运快递邮件激活", content, model.getEmail(), "");// 最后一个参数是激活码，已经放到content里了

		return SUCCESS;
	}

	// 属性驱动获取链接中的激活码
	private String activecode;

	public void setActivecode(String activecode) {
		this.activecode = activecode;
	}

	@Action(value = "customer_activeMail")
	public String activeMail() throws Exception {
		ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8");
		// 判断激活码是否有效
		// 先获取redis数据库中的激活码
		String activeCodeRedis = redisTemplate.opsForValue().get(model.getTelephone());
		if (activeCodeRedis == null || !activeCodeRedis.equals(activecode)) {
			// 激活码无效
			ServletActionContext.getResponse().getWriter().println("激活码无效，请登陆系统重新绑定邮箱！");
		} else {
			// 激活码有效
			// 判断是否重复绑定，根据客户表中的type字段，为1表示已经激活，为0表示没有激活
			// 调用crm_management系统根据电话号码查询客户
			Customer customer = WebClient.create(Constants.CRM_MANAGEMENT_URL + "/services/customerService")
					.path("/customer/telephone/" + model.getTelephone()).type(MediaType.APPLICATION_JSON)
					.accept(MediaType.APPLICATION_JSON).get(Customer.class);
			System.out.println(customer);
			if (customer != null && customer.getType() != 1) {
				// 更新客户的type值为1
				WebClient.create(Constants.CRM_MANAGEMENT_URL + "/services/customerService")
						.path("/updatetype/telephone/" + model.getTelephone()).type(MediaType.APPLICATION_JSON)
						.put(model);
				ServletActionContext.getResponse().getWriter().println("邮箱绑定成功！");
			} else {
				ServletActionContext.getResponse().getWriter().println("邮箱已经激活，无需重复绑定！");
			}
		}
		// 删除redis的激活码
		redisTemplate.delete(model.getTelephone());

		return NONE;
	}
	
	@Action(value="customer_login",results={@Result(name="success",type="redirect",location="index.html#/myhome"),
			@Result(name="input",type="redirect",location="login.html")})
	public String login() {
		//调用crm_management系统查询
		Customer customer = WebClient.create(Constants.CRM_MANAGEMENT_URL+"/services/customerService/customer/findCustomerByTelephoneAndPassword?telephone="+model.getTelephone()+"&password="+model.getPassword())
			.type(MediaType.APPLICATION_JSON)
			.accept(MediaType.APPLICATION_JSON)
			.get(Customer.class);
		if(customer == null) {
			System.out.println("用户名或密码错误！");
			return INPUT;
		}else {
			if(customer.getType() !=1) {
				System.out.println("账户尚未激活，请登陆邮箱激活后登陆！");
				return INPUT;
			}else {
				System.out.println("登陆成功！");
				//将用户信息存放到session中
				ServletActionContext.getRequest().getSession().setAttribute("customer", customer);
				return SUCCESS;
			}
		}
	}

}
